package cn.com.woxitech.dev.controller.api;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;

import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.EncryptionUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.common.SMSCodeUtils;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.AppService;
import cn.com.woxitech.dev.service.CatalogService;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.PrivilegeService;
import cn.com.woxitech.dev.service.QiniuService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.SMSCodeService;
import cn.com.woxitech.dev.service.SettingService;
import cn.com.woxitech.dev.service.UserService;
import cn.com.woxitech.dev.service.WeixinService;

@RestController
@RequestMapping("/luyan")
public class AuthorizationLUYANController {
	@Autowired
	WeixinService weixinService;
	@Autowired
	SettingService settingService;
	@Autowired
	PrivilegeService privilegeService;
	@Autowired
	QiniuService qiniuService;
	@Autowired
	RoomService roomService;
	@Autowired
	LectureService lectureService;
	@Autowired
	LecturePageService lecturePageService;
	@Autowired
	UserService userService;
	@Autowired
	SMSCodeService smsCodeService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	CatalogService catalogService;	
	@Autowired
	AppService appService;
	
	@RequestMapping(value="/h5login",method=RequestMethod.POST)
	public Object h5login(@RequestBody String body) throws JsonProcessingException, IOException {
		try {
			Map<String, Object> mp = new HashMap<String, Object>();
			
			JsonNode jsonNode = JSONUtils.toJson(body);
			String encode_token = jsonNode.get("token").asText();
			String token = EncryptionUtils.decode(encode_token);
			
			int pos = token.indexOf(';');
			String useruuid = token.substring(0,pos);
			long time = Long.parseLong(token.substring(pos+1));
			long now = System.currentTimeMillis();
			
			if(Math.abs(now - time) < 60000){//在时间允许范围内
				
				WmUser user = this.userService.getUserByUuid(useruuid);
				
				if(user == null){
					return APIResultFactory.fail();	
				}
				mp.put("uuid", user.getUuid());
				mp.put("name", user.getName());
				mp.put("headimgurl", user.getWxHeadimgurl());
				mp.put("unionid", user.getWxUnionid());
				mp.put("usertype", user.getUserType());
				
				return APIResultFactory.success(mp);	
			}else{
				return APIResultFactory.fail();	
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return APIResultFactory.fail();	
		}
	}
	
	@RequestMapping(value="/wxlogin",method=RequestMethod.POST)
	public Object wxlogin(@RequestBody String body) throws JsonProcessingException, IOException {
		try {
			Map<String, Object> mp = new HashMap<String, Object>();
			
			JsonNode jsonNode = JSONUtils.toJson(body);
			String wxunionid = jsonNode.get("unionid").asText();
			String accesstoken = jsonNode.get("accesstoken").asText();
			String openid = jsonNode.get("openid").asText();
			
			String systemType = jsonNode.get("systemType").asText();
			String nickname = jsonNode.get("nickname").asText();				
			
			String headimgurl = jsonNode.get("headimgurl").asText();
		
			WmUser user = userService.getUserByUnionId(wxunionid);
			Date now = new Date(System.currentTimeMillis());
			if(user == null){
				user = new WmUser();
				user.setCreatetime(new Date(System.currentTimeMillis()));
				user.setOpenOpenid(openid);
				user.setOpenAccessToken(accesstoken);
				user.setWxNickname(nickname);
				user.setName(nickname);
				user.setWxHeadimgurl(headimgurl);
				user.setWxUnionid(wxunionid);
				user.setUuid(UUID.randomUUID().toString());
				user.setLastlogin(now);
				this.userService.insertUser(user);
				
				mp.put("next", true);
				
			}else{
				
				if(user.getName().equals(user.getWxNickname())){
					user.setWxNickname(nickname);
					user.setName(nickname);	
				}else{
					user.setWxNickname(nickname);
				}
				user.setOpenOpenid(openid);
				user.setOpenAccessToken(accesstoken);
				user.setWxHeadimgurl(headimgurl);
				user.setWxUnionid(wxunionid);
				user.setLastlogin(now);
				if(user.getTel() == null || user.getTel().trim().length() == 0){
					mp.put("next", true);
					
				}else{
					mp.put("next", false);	
				}
				this.userService.updateUser(user);
				
			}
			
			mp.put("headimgurl", user.getWxHeadimgurl());
			mp.put("name", user.getName());
			mp.put("unionid", user.getWxUnionid());
			mp.put("useruuid", user.getUuid());
			mp.put("tel", user.getTel());
			mp.put("usertype", user.getUserType());
			
			return APIResultFactory.success(mp);
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();	
		}
	}
	
		 
	@RequestMapping(value="/login/tel/{tel}/smscode/{smscode}",method=RequestMethod.POST)
	public Object login_tel_smscode(@PathVariable String tel, @PathVariable String smscode) {
		
		
		String phoneNum = tel;
		String code = smscode;
		boolean isTrue = smsCodeService.validateSMSVerifyCode(phoneNum, code);
		if (isTrue) {
			WmUser user = userService.getUserByTel(tel);
			return APIResultFactory.success(user);
		}else {
			return APIResultFactory.fail();
		}
		
		
	}

	@RequestMapping(value="/login/tel/{tel}/pwd/{pwd}",method=RequestMethod.POST)
	public Object login_tel_pwd(@PathVariable String tel, @PathVariable String pwd) {
		
		
		String phoneNum = tel;
		String password = pwd;
		WmUser user = userService.getUserByTel(phoneNum);
		boolean isTrue = false;
		if(user != null ){
			isTrue = user.getPwd().equals(EncryptionUtils.MD5(password));
		}
		
		if (isTrue) {
			return APIResultFactory.success(user);
		}else {
			return APIResultFactory.success();
		}
		
		
	}
	
	@RequestMapping(value="/register/tel/{tel}/smscode/{smscode}/pwd/{pwd}",method=RequestMethod.POST)
	public Object register_tel_pwd(@PathVariable String tel,@PathVariable String smscode, @PathVariable String pwd) {
		
		
		String phoneNum = tel;
		String password = pwd;
		String code = smscode;
		
		
		WmUser user = userService.getUserByTel(phoneNum);
		
		if(user != null){
			return APIResultFactory.success("该手机号已经被注册");
		}
		
		boolean isTrue = smsCodeService.validateSMSVerifyCode(phoneNum, code);
				
		if (isTrue) {
			//验证成功
			WmUser new_user = new WmUser();
			Date now = new Date(System.currentTimeMillis());
			new_user.setCreatetime(now);
			new_user.setUuid(UUID.randomUUID().toString());
			new_user.setLastlogin(now);
			new_user.setTel(phoneNum);
			new_user.setPwd(EncryptionUtils.MD5(password));
			new_user.setName(phoneNum);
			this.userService.insertUser(new_user);
			
			return APIResultFactory.created();
		}else {
			//验证失败
			return APIResultFactory.success("验证码不正确或已过期");
		}
		
		
	}
	
	@RequestMapping(value="/reset/tel/{tel}/smscode/{smscode}/pwd/{pwd}",method=RequestMethod.POST)
	public Object reset_tel_pwd(@PathVariable String tel,@PathVariable String smscode, @PathVariable String pwd) {
		
		
		String phoneNum = tel;
		String password = pwd;
		String code = smscode;
		
		
		WmUser user = userService.getUserByTel(phoneNum);
		
		if(user == null){
			return APIResultFactory.success("该手机号未被注册");
		}
		
		boolean isTrue = smsCodeService.validateSMSVerifyCode(phoneNum, code);
				
		if (isTrue) {
			//验证成功
			user.setPwd(EncryptionUtils.MD5(password));
			this.userService.updateUser(user);
			
			return APIResultFactory.created();
		}else {
			//验证失败
			return APIResultFactory.success("验证码不正确或已过期");
		}
		
		
	}

	@RequestMapping(value="/code_send", method=RequestMethod.POST)
	public Object sendCode(@RequestBody String body){
		try{
			JsonNode jsonNode = JSONUtils.toJson(body);
			String phoneNum = jsonNode.get("phoneNum").asText();
			String code = smsCodeService.generateCode();
			smsCodeService.createSMSVerifyCodeInDB(phoneNum, code);
			System.out.println("code:" + code);
			
			SMSCodeUtils.sendSMSVerifyCode(phoneNum, code);
			
			return APIResultFactory.success();
		}catch(Exception e){
			e.printStackTrace();
			return APIResultFactory.fail();	
		}
		
	}
	
	@RequestMapping(value="/code_validate", method=RequestMethod.POST)
	public Object validateCode(@RequestBody String body) throws JsonProcessingException, IOException{
		JsonNode jsonNode = JSONUtils.toJson(body);
		String phoneNum = jsonNode.get("phoneNum").asText();
		String code = jsonNode.get("code").asText();
		boolean isTrue = smsCodeService.validateSMSVerifyCode(phoneNum, code);
		if (isTrue) {
			return APIResultFactory.success(true);
		}else {
			return APIResultFactory.success(false);
		}
	}
	
	@RequestMapping(value="/admin/user/{useruuid}/prove", method=RequestMethod.POST)
	public Object adminuser_prove(@PathVariable String useruuid, @RequestBody String body) throws JsonProcessingException, IOException{
		
		boolean isTrue = false;
		WmUser user = this.userService.getUserByUuid(useruuid);
		if(user == null){
			return APIResultFactory.success(false);
		}
		if(user.getUserType() == null || user.getUserType().equals("")){
			user.setUserType("1");
			isTrue = true;
			this.userService.updateUser(user);
		}
		if (isTrue) {
//			SMSCodeUtils.sendAdminUserProve(user.getTel(),user.getName());
			return APIResultFactory.success(true);
		}else {
			return APIResultFactory.success(false);
		}
	}
	@RequestMapping(value="/admin/user/{useruuid}/revoke", method=RequestMethod.POST)
	public Object adminuser_revoke(@PathVariable String useruuid, @RequestBody String body) throws JsonProcessingException, IOException{

		boolean isTrue = false;
		WmUser user = this.userService.getUserByUuid(useruuid);
		if(user == null){
			return APIResultFactory.success(false);
		}
		if(user.getUserType() == null || user.getUserType().equals("")){
		
		}else if(user.getUserType().equals("9")){
			
		}else if(user.getUserType().equals("1")){
			user.setUserType(null);
			isTrue = true;
			this.userService.updateUserHard(user);
		}
		if (isTrue) {
//			SMSCodeUtils.sendAdminUserProve(user.getTel(),user.getName());
			return APIResultFactory.success(true);
		}else {
			return APIResultFactory.success(false);
		}
	}
	@RequestMapping(value="/admin/user/{useruuid}/admin_revoke", method=RequestMethod.POST)
	public Object adminuser_admin_revoke(@PathVariable String useruuid, @RequestBody String body) throws JsonProcessingException, IOException{

		boolean isTrue = false;
		WmUser user = this.userService.getUserByUuid(useruuid);
		if(user == null){
			return APIResultFactory.success(false);
		}
		if(user.getUserType() == null || user.getUserType().equals("")){
			
		}else if(user.getUserType().equals("1")){
			
		}else if(user.getUserType().equals("9")){
			user.setUserType("1");
			isTrue = true;
			this.userService.updateUser(user);
		}
		if (isTrue) {
			return APIResultFactory.success(true);
		}else {
			return APIResultFactory.success(false);
		}
	}
	@RequestMapping(value="/admin/user/add_admin", method=RequestMethod.POST)
	public Object adminuser_admin_add(@RequestBody String body) throws JsonProcessingException, IOException{

		JsonNode jsonNode = JSONUtils.toJson(body);
		String tel = null;
		if(jsonNode.has("tel")){
			tel = jsonNode.get("tel").asText(); 
		}else{
			return APIResultFactory.success(false);
		}
		if(tel == null){
			return APIResultFactory.success(false);
		}
		
		boolean isTrue = false;
		WmUser user = this.userService.getUserByTel(tel);
		if(user == null){
			return APIResultFactory.success(false);
		}
		
		user.setUserType("9");
		isTrue = true;
		this.userService.updateUser(user);
		
		if (isTrue) {
			return APIResultFactory.success(true);
		}else {
			return APIResultFactory.success(false);
		}
	}
	
	@RequestMapping(value="/login/encryvalid", method=RequestMethod.POST)
	public Object login_encryvalid(@RequestBody String body) {
		
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
		
			String val_encry = jsonNode.get("encry").asText();

			//?unionid=o9SI3t5zIxt0rkk9_4w8AshIJcWI&time=1470196134820
			String val = EncryptionUtils.decode(val_encry);

			long now = System.currentTimeMillis();
			
			int len1 = "?unionid=".length();
			int len2 = "&time=".length();
			int len = val.length();
			int p1 = val.indexOf("&time=");
			
			
			String id = val.substring(len1, p1);
			long time = Long.parseLong(val.substring(p1 + len2));
			
//			if((now - time)/1000 > 3600){
//				return APIResultFactory.fail("认证已超时请重新登录");
//			} 
			
			WmUser user = this.userService.getUserByUnionId(id);
			if(user == null){
				return APIResultFactory.fail("用户权限认证不正确请重新登录");
			}
			
			if(user.getUserType() == null || user.getUserType().equals("")){
				return APIResultFactory.fail("您还没有获得开启直播的权限，请在APP中完善您得个人信息并等待审核");
			}
			mp.put("useruuid", user.getUuid());
			mp.put("username", user.getName());
			mp.put("isAdmin", "0");
			mp.put("headimgurl", user.getWxHeadimgurl());
			
			return APIResultFactory.success(mp);
		
		
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return APIResultFactory.fail("用户权限认证不正确请重新登录");
	}
}
